package com.jgssp.ad.sdk.mediation.adapter;

import android.app.Activity;
import android.content.Context;
import android.util.Log;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.mediation.MediationConstant;
import com.bytedance.sdk.openadsdk.mediation.bridge.custom.native_ad.MediationCustomNativeLoader;
import com.bytedance.sdk.openadsdk.mediation.custom.MediationCustomServiceConfig;
import com.jgssp.ad.sdk.mediation.utils.PriceUtil;
import com.jgssp.ad.sdk.mediation.utils.ThreadUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.jiguang.jgssp.ad.ADJgNativeAd;
import cn.jiguang.jgssp.ad.data.ADJgNativeAdInfo;
import cn.jiguang.jgssp.ad.data.ADJgNativeExpressAdInfo;
import cn.jiguang.jgssp.ad.data.ADJgNativeFeedAdInfo;
import cn.jiguang.jgssp.ad.entity.ADJgAdSize;
import cn.jiguang.jgssp.ad.entity.ADJgExtraParams;
import cn.jiguang.jgssp.ad.error.ADJgError;
import cn.jiguang.jgssp.ad.listener.ADJgNativeAdListener;
import cn.jiguang.jgssp.util.ADJgDisplayUtil;

/**
 * @Description: 信息流广告适配器
 */
public class CustomerNativeAdapter extends MediationCustomNativeLoader {

    private List<GmNativeExpressAd> nativeExpressAds;
    private List<GmNativeAd> nativeAds;

    @Override
    public void load(final Context context, AdSlot adSlot, final MediationCustomServiceConfig serviceConfig) {

        ThreadUtils.runOnUIThreadByThreadPool(new Runnable() {
            @Override
            public void run() {

                if (!(context instanceof Activity)) {
                    callLoadFail(-1, "JgSSP Context must be Activity");
                    return;
                }

                int widthPixels = context.getResources().getDisplayMetrics().widthPixels - ADJgDisplayUtil.dp2px(20);
                // 创建信息流广告实例
                ADJgNativeAd nativeAd = new ADJgNativeAd((Activity) context);
                // 创建额外参数实例
                ADJgExtraParams extraParams = new ADJgExtraParams.Builder()
                        // 设置整个广告视图预期宽高(目前仅头条平台需要，没有接入头条可不设置)，单位为px，高度如果小于等于0则高度自适应
                        .adSize(new ADJgAdSize(widthPixels, 0))
                        // 设置广告视图中MediaView的预期宽高(目前仅Inmobi平台需要,Inmobi的MediaView高度为自适应，没有接入Inmobi平台可不设置)，单位为px
                        .nativeAdMediaViewSize(new ADJgAdSize((int) (widthPixels - 24 * context.getResources().getDisplayMetrics().density)))
                        .nativeAdPlayWithMute(true)
                        .build();
                // 设置一些额外参数，有些平台的广告可能需要传入一些额外参数，如果有接入头条、Inmobi平台，如果包含这些平台该参数必须设置
                nativeAd.setLocalExtraParams(extraParams);
                // 设置广告监听
                nativeAd.setListener(new ADJgNativeAdListener() {
                    @Override
                    public void onRenderFailed(ADJgNativeAdInfo adJgNativeAdInfo, ADJgError adJgError) {
                    }

                    @Override
                    public void onRenderSuccess(ADJgNativeAdInfo adJgNativeAdInfo) {

                    }

                    @Override
                    public void onAdReceive(List<ADJgNativeAdInfo> list) {
                        if (list == null || list.isEmpty()) {
                            callLoadFail(-2, "no ad");
                            return;
                        }

                        if (isExpressRender()) {
                            nativeExpressAds = new ArrayList<>();
                            for (ADJgNativeAdInfo nativeAdInfo : list) {
                                if (nativeAdInfo instanceof ADJgNativeExpressAdInfo) {
                                    GmNativeExpressAd gmNativeExpressAd = new GmNativeExpressAd(context, (ADJgNativeExpressAdInfo) nativeAdInfo, getBiddingType());
                                    if (isClientBidding()) {
                                        //bidding广告类型，回传竞价广告价格 单位：分
                                        gmNativeExpressAd.setBiddingPrice(PriceUtil.toCent(nativeAdInfo.getECPM()));
                                    }
                                    nativeExpressAds.add(gmNativeExpressAd);
                                }
                            }
                            callLoadSuccess(nativeExpressAds);
                        } else if (isNativeAd()) {
                            nativeAds = new ArrayList<>();
                            for (ADJgNativeAdInfo nativeAdInfo : list) {
                                if (nativeAdInfo instanceof ADJgNativeFeedAdInfo) {
                                    GmNativeAd gmNativeAd = new GmNativeAd((ADJgNativeFeedAdInfo) nativeAdInfo, getBiddingType());
                                    nativeAds.add(gmNativeAd);
                                    if (isClientBidding()) {
                                        //bidding广告类型，回传竞价广告价格 单位：分
                                        gmNativeAd.setBiddingPrice(PriceUtil.toCent(nativeAdInfo.getECPM()));
                                    }
                                }
                            }
                            callLoadSuccess(nativeAds);
                        } else {
                            callLoadFail(-3, "渲染类型未适配");
                        }
                    }

                    @Override
                    public void onAdExpose(ADJgNativeAdInfo adInfo) {
                        if (isExpressRender()) {
                            if (getGmNativeExpressAd(adInfo) != null) {
                                getGmNativeExpressAd(adInfo).callAdShow();
                            }
                        } else if (isNativeAd()) {
                            if (getGmNativeAd(adInfo) != null) {
                                getGmNativeAd(adInfo).callAdShow();
                            }
                        }
                    }

                    @Override
                    public void onAdClick(ADJgNativeAdInfo adInfo) {
                        if (isExpressRender()) {
                            if (getGmNativeExpressAd(adInfo) != null) {
                                getGmNativeExpressAd(adInfo).callAdClick();
                            }
                        } else if (isNativeAd()) {
                            if (getGmNativeAd(adInfo) != null) {
                                getGmNativeAd(adInfo).callAdClick();
                            }
                        }
                    }

                    @Override
                    public void onAdClose(ADJgNativeAdInfo adInfo) {
                        if (isExpressRender()) {
                            if (getGmNativeExpressAd(adInfo) != null) {
                                getGmNativeExpressAd(adInfo).clear();
                            }
                        } else if (isNativeAd()) {
                            if (getGmNativeAd(adInfo) != null) {
                                getGmNativeAd(adInfo).callDislikeSelected(0, "关闭");
                            }
                        }
                    }

                    @Override
                    public void onAdFailed(ADJgError adJgError) {
                        callLoadFail(adJgError.getCode(), adJgError.getError());
                    }
                });
                if (serviceConfig != null) {
                    nativeAd.loadAd(serviceConfig.getADNNetworkSlotId());
                }
            }
        });
    }

    private GmNativeExpressAd getGmNativeExpressAd(ADJgNativeAdInfo adInfo) {
        for (int i = 0; i < nativeExpressAds.size(); i++) {
            if (nativeExpressAds.get(i).getNativeExpressAdInfo() == adInfo) {
                return nativeExpressAds.get(i);
            }
        }
        return null;
    }

    private GmNativeAd getGmNativeAd(ADJgNativeAdInfo adInfo) {
        for (int i = 0; i < nativeAds.size(); i++) {
            if (nativeAds.get(i).getNativeAdInfo() == adInfo) {
                return nativeAds.get(i);
            }
        }
        return null;
    }

    /**
     * 是否clientBidding广告
     *
     * @return
     */
    public boolean isClientBidding() {
        return getBiddingType() == MediationConstant.AD_TYPE_CLIENT_BIDING;
    }

    @Override
    public void receiveBidResult(boolean win, double winnerPrice, int loseReason, Map<String, Object> extra) {
    }

}
